import re, string, itertools
from collections import defaultdict, OrderedDict
from StringIO import StringIO

def read_scenarios() :
    lines = open("all_scenarios.py").readlines()

    scenarios = defaultdict( lambda : {} )
    all_initiators = set()

    for li in range(len(lines)) :
        if lines[li].find("@scenario") == 0 and lines[li+1].find("def") == 0 :
            usecase = re.sub('\(.*', "", lines[li+1].split()[1])
            for lk in range(li+2,len(lines)) :
                if string.strip(lines[lk]) == "" : break
                initiator, read_bw, write_bw = \
                [x.strip() for x in re.sub("[(,]", "", lines[lk].split(")")[0]).split()]
                read_bw = string.atof(read_bw)
                write_bw = string.atof(write_bw)
                scenarios[usecase][initiator] = [read_bw, write_bw]
                all_initiators.add(initiator)

    all_initiators = list(all_initiators)

    return all_initiators, scenarios

link_descriptions = OrderedDict([
    ("trt_top_tpdp", {"USB0", "USB1", "DISP"}),
    ("trt_center_tpdp", {"SFC0", "SFC1", "SDHOST0", "SDHOST1", "SDHOST2", "ETH0", "NAND", "MDC"}),
    ("tleft_ddr", {"VPP", "VPP_ESM", "ISP"}),
    ("tgpu_ddr", {"GPU0", "GPU1"}),
    ("tcpu_ddr", {"CPU0", "CPU1", "CPU2"}), # missing info!
    ("tdec_ddr", {"VXD", "VXE", "CIP2_0", "CIP2_1", "ISP", "VPP", "VPP_ESM", "JTAG"}), # missing info!
    ("tpdp_ddr", {"PDP0", "PDP1", "SEC", "RPU", "MDC", "SDHOST2", "SDHOST1", "SDHOST0", "ETH0", "NAND", "SFC0", "SFC1", "USB1", "USB0", "DISP"}),
    ("tddr",None),
])

if __name__=="__main__" :
    all_initiators, scenarios = read_scenarios()
    path_util_csv = "paths_utilization.csv"

    ofp = open(path_util_csv, "w")
    #write column headers
    print >> ofp, ",", ",,".join(link_descriptions.keys()), ",,",
    print >> ofp, ",,".join(all_initiators)
    for usecase in scenarios :
        print "*****", usecase
        for initiator, (rbw,wbw) in scenarios[usecase].items() :
            print initiator, rbw, wbw
        print >> ofp, "%s," % (usecase),
        for path, initiators in link_descriptions.items() :
            if initiators == None :
                common_initiators = scenarios[usecase].keys()
            else :
                common_initiators = initiators.intersection( set(scenarios[usecase].keys()) )
            path_total_rbw = sum( [scenarios[usecase][init][0] for init in common_initiators] )
            path_total_wbw = sum( [scenarios[usecase][init][1] for init in common_initiators] )
            print >> ofp, path_total_rbw, ",", path_total_wbw, ",",
        for initiator in all_initiators :
            try :
                rbw, wbw = scenarios[usecase][initiator]
            except KeyError :
                rbw, wbw = "", ""
            print >> ofp, rbw, ",", wbw, ",",
        print >> ofp, ""
    ofp.close()

    # append max of each column as final rows
    lines = open(path_util_csv).readlines()
    l1 = StringIO()
    l2 = StringIO()
    for fi in range(len(lines[0].split(","))) :
        max_val, max_usecase = None, None
        for l in lines :
            flds = l.split(",")
            try :
                val = string.atof(flds[fi])
            except ValueError :
                continue
            if max_val is None or val > max_val :
                max_val = val
                max_usecase = flds[0]
        print >> l1, str(max_val), ",",
        print >> l2, str(max_usecase), ",",
        #print >> ofp, "%s (%s)," % (str(max_val), str(max_usecase)),
    ofp = open(path_util_csv, "a")
    print >> ofp, l1.getvalue()
    print >> ofp, l2.getvalue()
    ofp.close()
    l1.close() ; l2.close()
